package cn.y.operation.framework.utils.dev;

import cn.y.operation.framework.constants.Constants;
import cn.y.operation.framework.pojo.QRCodePojo;
import com.alibaba.fastjson.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import org.apache.commons.codec.binary.Base64;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @ClassName: QRCodeUtils
 * @author: 叶子豪
 * @create: 2020-07-15 15:49
 */
public class QRCodeUtils {

    public static byte[] encryptionCodeToByte(QRCodePojo qrCodePojo) throws IOException, WriterException {
        return getQRCodeImage(encryptionCodeToString(qrCodePojo), Constants.QRCodeWidth, Constants.QRCodeHeight);
    }

    public static String encryptionCodeToString(QRCodePojo qrCodePojo) {
        qrCodePojo.setEndTime(String.valueOf(System.currentTimeMillis() / 1000 + 86400));
        String jsonObj = JSONObject.toJSONString(qrCodePojo);
        String baseCode = Base64.encodeBase64String(jsonObj.getBytes(StandardCharsets.UTF_8));
        System.out.println(baseCode);
        return baseCode;
    }

    public static byte[] getQuestionQRCode(String text) throws IOException, WriterException {
        return getQRCodeImage(text, Constants.QRCodeWidth, Constants.QRCodeHeight);
    }

    private static byte[] getQRCodeImage(String text, int width, int height) throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
        ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
        return pngOutputStream.toByteArray();
    }
}